package com.xzcs.service.tools;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xzcs.mapper.tools.GeneratorMapper;
import com.xzcs.service.BaseService;
import com.xzcs.util.common.GeneratorUtils;
import com.xzcs.util.common.StringUtils;
import com.xzcs.util.web.RequestUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipOutputStream;

@Service
public class GeneratorService extends BaseService {

	@Autowired
	private GeneratorMapper generatorMapper;
	
	public PageInfo<Map<String, Object>> findTables(HttpServletRequest request){
		String pageNum = RequestUtils.getValue(request, "page");//页数
		String pageSize = RequestUtils.getValue(request, "rows");//每页条数
		pageNum = pageNum.equals("") ? "1" : pageNum;
		pageSize = pageSize.equals("") ? getDefaultPageSize() : pageSize;
		Map<String, Object> params = RequestUtils.getRequestMap(request);
		PageHelper.startPage(StringUtils.toInt(pageNum), StringUtils.toInt(pageSize));
		List<Map<String, Object>> list = generatorMapper.findTables(params);
		PageInfo<Map<String, Object>> page = new PageInfo<Map<String, Object>>(list);
		return page;
    }

    public byte[] generatorCode(HttpServletRequest request) {
        String[] tableNames = RequestUtils.getValues(request, "tableName");
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);
        for(String tableName : tableNames){
            //查询表信息
            Map<String, Object> table = generatorMapper.findTable(tableName);
            //查询列信息
            List<Map<String, Object>> columns = generatorMapper.findTableColumns(tableName);
            //生成代码
            GeneratorUtils.generatorCode(request, table, columns, zip);
        }
        IOUtils.closeQuietly(zip);
        return outputStream.toByteArray();
    }
}
